package com.yonyou.ucf.mdf.app.isvdxq.other.service;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.yonyou.ucf.mdf.app.isvdxq.other.mapper.impl.OrgBaseMapperImpl;
import com.yonyou.ucf.mdf.app.isvdxq.yonyisv.model.EventContent;
import com.yonyou.ucf.mdf.app.isvdxq.other.entity.OrgBaseEntity;
import com.yonyou.ucf.mdf.app.isvdxq.other.model.ContentBean;
import com.yonyou.ucf.mdf.app.isvdxq.other.model.OrgBaseBean;
import com.yonyou.ucf.mdf.app.isvdxq.utils.RequestTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class OrgBaseService {
    @Autowired
    private OrgBaseMapperImpl orgBaseMapper;

    public OrgBaseEntity SelectById(String id, String orgtype){
        return orgBaseMapper.selectById(id,orgtype);
    }

    public Boolean CheckEntity(String Id, String orgtype, String tenant_id) {
        int rInt = orgBaseMapper.selectCount(Id, orgtype, tenant_id);
        if (rInt > 0) return true;
        else return false;
    }
    public Boolean CheckEntityByOrgId(String Id) {
        int rInt = orgBaseMapper.selectCountByOrgId(Id);
        if (rInt > 0) return true;
        else return false;
    }

    public Integer InsertEntity(OrgBaseEntity entity){
        return orgBaseMapper.insert(entity);
    }

    public Integer UpdateEntity(OrgBaseEntity entity){
        return orgBaseMapper.updateByPrimaryKey(entity);
    }

    public Integer DeleteByOrgId(String id){
        return orgBaseMapper.deleteByPrimaryKeyByOrgId(id);
    }


    public Integer EventEdit(EventContent content) throws IOException {
        System.out.println(content.getContent());
        ContentBean obj = RequestTool.getBean(content.getContent(), ContentBean.class);
        String jsonString = obj.getArchive().replace("detail!id", "detailid").replace("detail!", "");
        OrgBaseBean orgBaseBean = RequestTool.getBean(jsonString, OrgBaseBean.class);
        String jsonStr = new Gson().toJson(orgBaseBean);
        OrgBaseEntity orgBaseEntity = RequestTool.getBean(jsonStr, OrgBaseEntity.class);
        orgBaseEntity.setTenant_id(obj.getTenantId());
        System.out.println(JSON.toJSONString(orgBaseEntity));
        Boolean flag = CheckEntity(orgBaseEntity.getId(), orgBaseEntity.getOrgtype(), orgBaseEntity.getTenant_id());
        if (flag) {
            int rInt = UpdateEntity(orgBaseEntity);
            return rInt;
        } else {
            int rInt = InsertEntity(orgBaseEntity);
            return rInt;
        }
    }

    public Integer EventDel(EventContent content) throws IOException {
        System.out.println(content.getContent());
        ContentBean obj = RequestTool.getBean(content.getContent(), ContentBean.class);
        Boolean flag = CheckEntityByOrgId(obj.getId());
        if (flag) {
            int rInt = DeleteByOrgId(obj.getId());
            return rInt;
        }
        return 0;
    }
}
